import React, { useState }  from 'react';
import './index.less';
import api from '../../../axios'
import { Row, Table, Modal, DatePicker, Divider, Button, Image,
  Form,
  Select,
  Switch,
  Input,
  message,
Upload, } from 'antd';
import { InboxOutlined, UploadOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import EditModal from '../components/editSwiper'

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
};
const normFile = (e) => {
  console.log('Upload event:', e);
  if (Array.isArray(e)) {
    return e;
  }
  return e?.fileList;
};

const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};


class index extends React.Component {
    constructor(props) {
        super(props);
        this.state = { 
            visible: false,
            loading: true,
            fileloading: false,
            imageUrl: '',
            initialValues: {},
            editModalVis: false,
            pagination: {
              current: 1,
              size: 10,
              pageSize: 10,
              total: 0
            },
        };
    }

    showModal = () => {
        this.setState({
            visible: true,
        });
    };
    
    hideModal = () => {
        this.setState({
            visible: false,
        });
    };

    componentDidMount(){
        this.getData()
    }

    
    getData = async () => {
      const { current, size, pageSize } = this.state.pagination;
      this.setState({ loading: true })

      let res = await api.ajax({
          method: 'get',
          url: `/carousel/lis?page=${current}&size=${size}`,
      });

      
      const pagination = { ...this.state.pagination };

      pagination.total = res.data.total;


      this.setState({
          data: res.data,
          loading: false,
          pagination
      })
    }

    addSwiper = async ({ url, is_show, des, sort }) => {
      let res = await api.ajax({
          method: 'post',
          url: `/carousel/add`,
          data: {
            image: this.state.imageUrl,
            url,
            is_show: is_show == undefined || is_show == true ? true : false,
            des,
            sort,
          }
      });
      message.success(res.msg);
      this.setState({ pagination: { current: 1, size: 20, pageSize: 10, total: 0 }, visible: false })
      this.getData()
      // console.log(res);
    } 
    editMoadl = (record) => {
      this.setState({
        initialValues: record,
        editModalVis: true
      })
    }

    
    render() {
      const columns = [
          {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
          },
          {
            title: '轮播详情',
            dataIndex: 'des',
            key: 'des',
          },
          {
            title: '轮播图片',
            dataIndex: 'image',
            key: 'image',
            width: '200px',
            render: (text, record) => (
              <span>
                <Image width={150} src={record.image}/>
              </span>
            ),
          },
          {
            title: '文件类型',
            dataIndex: 'file_type',
            key: 'file_type',
          },
          {
            title: '是否显示',
            dataIndex: 'is_show',
            key: 'is_show',
            render: (text, record) => (
              <span>
                { record.is_show ? '是' : '否'}
              </span>
            ),
          },
          {
            title: '路径',
            dataIndex: 'url',
            key: 'url',
          },
          {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
          },
          {
            title: '创建时间',
            dataIndex: 'create_time',
            key: 'create_time',
            width: '200px'
          },
          {
            title: '更新时间',
            dataIndex: 'update_time',
            key: 'update_time',
            width: '200px'
          },
          {
            title: '操作',
            key: 'action',
            fixed: 'right',
            render: (text, record) => (
              <span>
                <a onClick={() => this.editMoadl(record)}>编辑</a>
              </span>
            ),
          },
          
      ];    


      const onFinish = (values) => {
        console.log( values);
        this.addSwiper(values)
        //i1.hdslb.com/bfs/archive/e745631c211a5856f1e7f0679af1672a320a7da9.jpg@672w_378h_1c_!web-home-common-cover

      };

      const handleChange = (info) => {
        const { fileList } = info
        let length = fileList.length
        let { response } = fileList[length - 1]
        if (info.file.status === 'uploading') {
          this.setState({
            fileloading: false
          })
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          getBase64(info.file.originFileObj, (url) => {
            this.setState({
              fileloading: false,
              imageUrl: response.data
            })
          });
        }
      };

      const { fileloading, imageUrl, initialValues, editModalVis } = this.state
      const uploadButton = (
        <div>
          {fileloading ? <LoadingOutlined /> : <PlusOutlined />}
          <div
            style={{
              marginTop: 8,
            }}
          >
            Upload
          </div>
        </div>
      );

      const onChange = (pagination, filters, sorter) => {
        console.log('params', pagination, filters, sorter);
        this.setState({
          pagination
        }, () => this.getData())
      }

        return (
           <>
             <div className='wapper'>
                <div className='header_title'>
                    <Button type="primary" onClick={() => this.setState({ visible: true }) }>添加轮播</Button>
                </div>
                <Table
                    columns={columns}
                    dataSource={this.state.data}
                    onChange={onChange}
                    pagination={this.state.pagination}
                    loading={this.state.loading}
                    scroll={{ x: 1500, y: 1000 }}
                />
             </div>
             
             <Modal
                  title="添加轮播"
                  width={800}
                  visible={this.state.visible}
                  onCancel={this.hideModal}
                  onOk={() => this.onOk(this.state.data3)}
                  okText="保存"
                  footer={false}
                  cancelText="取消"
              >
                  <Form
                    name="validate_other"
                    {...formItemLayout}
                    onFinish={onFinish}
                    initialValues={{
                      'input-number': 3,
                      'checkbox-group': ['A', 'B'],
                      rate: 3.5,
                    }}
                  >

                    <Form.Item
                        label="轮播图详情"
                        name="des"
                        rules={[{ required: true, message: '请输入轮播图详情' }]}
                      >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="路径"
                        name="url"
                        rules={[{ required: true, message: '请输入路径' }]}
                      >
                        <Input />
                    </Form.Item>
                    
                    <Form.Item name="is_show" label="是否显示开关" valuePropName="checked">
                      <Switch defaultChecked value={true}/>
                    </Form.Item>


                    <Form.Item
                        label="排序（排序，越小越靠前）"
                        name="sort"
                        rules={[{ required: true, message: '请输入排序' }]}
                      >
                        <Input />
                    </Form.Item>

                    <Form.Item
                      name="upload"
                      label="上传轮播图"
                      valuePropName="fileList"
                      getValueFromEvent={normFile}
                      rules={[{ required: true, message: '请选择图片' }]}
                    >
                        <Upload
                          name="file"
                          listType="picture-card"
                          className="avatar-uploader"
                          showUploadList={false}
                          action="/common/Upload/image"
                          beforeUpload={beforeUpload}
                          onChange={handleChange}
                        >
                          {imageUrl ? (
                            <img
                              src={imageUrl}
                              alt="avatar"
                              style={{
                                width: '100%',
                              }}
                            />
                          ) : (
                            uploadButton
                          )}
                        </Upload>
                    </Form.Item>

                    <Form.Item wrapperCol={{ span: 12, offset: 6 }}>
                      <Button type="primary" htmlType="submit">
                        保存
                      </Button>
                    </Form.Item>
                  </Form>
              </Modal>

                
              {
                editModalVis && 
                <EditModal
                  initialValues={initialValues}
                  cancelModal={() => {
                    this.setState({ editModalVis: false, pagination: { current: 1, size: 10, pageSize: 10, total: 0 } })
                    this.getData()
                  }}
                />
              }
           </>
        );
    }
}

export default index;